package com.lykj.modules.system.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lykj.modules.shop.entity.*;
import com.lykj.modules.shop.mapper.UserOrderMapper;
import com.lykj.modules.shop.service.*;
import com.lykj.modules.shop.znapi.ZnApiUtils;
import com.lykj.modules.system.service.*;
import lombok.AllArgsConstructor;
import com.lykj.common.cache.DictCache;
import com.lykj.common.cache.ParamCache;
import com.lykj.common.cache.SysCache;
import com.lykj.common.cache.UserCache;
import com.lykj.common.constant.CommonConstant;
import com.lykj.common.constant.TenantConstant;
import com.lykj.common.enums.DictEnum;
import com.lykj.core.log.exception.ServiceException;
import com.lykj.core.mp.base.BaseServiceImpl;
import com.lykj.core.mp.support.Condition;
import com.lykj.core.mp.support.Query;
import com.lykj.core.secure.utils.AuthUtil;
import com.lykj.core.tenant.LykjTenantProperties;
import com.lykj.core.tool.constant.LykjConstant;
import com.lykj.core.tool.jackson.JsonUtil;
import com.lykj.core.tool.support.Kv;
import com.lykj.core.tool.utils.*;
import com.lykj.modules.auth.enums.UserEnum;
import com.lykj.modules.system.entity.*;
import com.lykj.modules.system.excel.UserExcel;
import com.lykj.modules.system.mapper.UserMapper;
import com.lykj.modules.system.vo.UserVO;
import com.lykj.modules.system.wrapper.UserWrapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

import static com.lykj.common.constant.CommonConstant.DEFAULT_PARAM_PASSWORD;

/**
 * 服务实现类
 *
 * @author cxl
 */
@Service
@AllArgsConstructor
public class UserServiceImpl extends BaseServiceImpl<UserMapper, User> implements UserService {
	private static final String GUEST_NAME = "guest";
	private static final String TENANT_ID = "tenantId";
	private static final String PARENT_ID = "parentId";

	private final UserDeptService userDeptService;
	private final UserOauthService userOauthService;
	private final RoleService roleService;
	private final LykjTenantProperties tenantProperties;
	private final ZnApiUtils znApiUtils;
	private final SMSService smsService; // 短信服务
	private final UserBillService userBillService;
	private final ParamService paramService;
	private final UserBonusService userBonusService;
	private final UserExtractService userExtractService;
//	private final StoreProductService storeProductService;
	private final UserOrderMapper userOrderMapper;
//	private final StoreCategoryService storeCategoryService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean submit(User user) {
		if (StringUtil.isBlank(user.getTenantId())) {
			user.setTenantId(LykjConstant.ADMIN_TENANT_ID);
		}
		String tenantId = user.getTenantId();
		Tenant tenant = SysCache.getTenant(tenantId);
		if (Func.isNotEmpty(tenant)) {
			Integer accountNumber = tenant.getAccountNumber();
			if (tenantProperties.getLicense()) {
				String licenseKey = tenant.getLicenseKey();
				String decrypt = DesUtil.decryptFormHex(licenseKey, TenantConstant.DES_KEY);
				accountNumber = JsonUtil.parse(decrypt, Tenant.class).getAccountNumber();
			}
			Long tenantCount = baseMapper.selectCount(Wrappers.<User>query().lambda().eq(User::getTenantId, tenantId));
			if (accountNumber != null && accountNumber > 0 && accountNumber <= tenantCount) {
				throw new ServiceException("当前租户已到最大账号额度!");
			}
		}
		if (Func.isNotEmpty(user.getPassword())) {
			user.setPassword(DigestUtil.encrypt(user.getPassword()));
		}
		Long userCount = baseMapper.selectCount(Wrappers.<User>query().lambda().eq(User::getTenantId, tenantId).eq(User::getAccount, user.getAccount()));
		if (userCount > 0L && Func.isEmpty(user.getId())) {
			throw new ServiceException(StringUtil.format("当前用户 [{}] 已存在!", user.getAccount()));
		}
		return save(user) && submitUserDept(user);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean updateUser(User user) {
		String tenantId = user.getTenantId();
		Long userCount = baseMapper.selectCount(
			Wrappers.<User>query().lambda()
				.eq(User::getTenantId, tenantId)
				.eq(User::getAccount, user.getAccount())
				.notIn(User::getId, user.getId())
		);
		if (userCount > 0L) {
			throw new ServiceException(StringUtil.format("当前用户 [{}] 已存在!", user.getAccount()));
		}
		return updateUserInfo(user) && submitUserDept(user);
	}

	@Override
	public boolean updateUserInfo(User user) {
		user.setPassword(null);
		return updateById(user);
	}

	private boolean submitUserDept(User user) {
		List<Long> deptIdList = Func.toLongList(user.getDeptId());
		List<UserDept> userDeptList = new ArrayList<>();
		deptIdList.forEach(deptId -> {
			UserDept userDept = new UserDept();
			userDept.setUserId(user.getId());
			userDept.setDeptId(deptId);
			userDeptList.add(userDept);
		});
		userDeptService.remove(Wrappers.<UserDept>update().lambda().eq(UserDept::getUserId, user.getId()));
		return userDeptService.saveBatch(userDeptList);
	}

	@Override
	public IPage<User> selectUserPage(IPage<User> page, User user, Long deptId, String tenantId) {
		List<Long> deptIdList = SysCache.getDeptChildIds(deptId);
		return page.setRecords(baseMapper.selectUserPage(page, user, deptIdList, tenantId));
	}

	@Override
	public IPage<UserVO> selectUserSearch(UserVO user, Query query) {
		LambdaQueryWrapper<User> queryWrapper = Wrappers.<User>query().lambda();
		String tenantId = AuthUtil.getTenantId();
		if (StringUtil.isNotBlank(tenantId)) {
			queryWrapper.eq(User::getTenantId, tenantId);
		}
		if (StringUtil.isNotBlank(user.getName())) {
			queryWrapper.like(User::getName, user.getName());
		}
		if (StringUtil.isNotBlank(user.getDeptName())) {
			String deptIds = SysCache.getDeptIdsByFuzzy(AuthUtil.getTenantId(), user.getDeptName());
			if (StringUtil.isNotBlank(deptIds)) {
				queryWrapper.and(wrapper -> {
					List<String> ids = Func.toStrList(deptIds);
					ids.forEach(id -> wrapper.like(User::getDeptId, id).or());
				});
			}
		}
		if (StringUtil.isNotBlank(user.getPostName())) {
			String postIds = SysCache.getPostIdsByFuzzy(AuthUtil.getTenantId(), user.getPostName());
			if (StringUtil.isNotBlank(postIds)) {
				queryWrapper.and(wrapper -> {
					List<String> ids = Func.toStrList(postIds);
					ids.forEach(id -> wrapper.like(User::getPostId, id).or());
				});
			}
		}
		IPage<User> pages = this.page(Condition.getPage(query), queryWrapper);
		return UserWrapper.build().pageVO(pages);
	}

	@Override
	public User userByAccount(String tenantId, String account) {
		return baseMapper.selectOne(Wrappers.<User>query().lambda().eq(User::getTenantId, tenantId).eq(User::getAccount, account).eq(User::getIsDeleted, LykjConstant.DB_NOT_DELETED));
	}

	@Override
	public UserInfo userInfo(Long userId) {
		User user = baseMapper.selectById(userId);
		return buildUserInfo(user);
	}

	@Override
	public UserInfo userInfo(String tenantId, String account, String password) {
		User user = baseMapper.getUser(tenantId, account, password);
		return buildUserInfo(user);
	}

	@Override
	public UserInfo userInfo(String tenantId, String account, String password, UserEnum userEnum) {
		User user = baseMapper.getUser(tenantId, account, password);
		return buildUserInfo(user, userEnum);
	}

	@Override
	public UserInfo userInfo(String tenantId, String account, UserEnum userEnum) {
		User user = baseMapper.getUserInfo(tenantId, account);
		return buildUserInfo(user, userEnum);
	}

	private UserInfo buildUserInfo(User user) {
		return buildUserInfo(user, UserEnum.WEB);
	}

	private UserInfo buildUserInfo(User user, UserEnum userEnum) {
		if (ObjectUtil.isEmpty(user)) {
			return null;
		}
		UserInfo userInfo = new UserInfo();
		userInfo.setUser(user);
		if (Func.isNotEmpty(user)) {
			List<String> roleAlias = roleService.getRoleAliases(user.getRoleId());
			userInfo.setRoles(roleAlias);
		}
		// 根据每个用户平台，建立对应的detail表，通过查询将结果集写入到detail字段
		Kv detail = Kv.create().set("type", userEnum.getName());
		if (userEnum == UserEnum.WEB) {
			UserWeb userWeb = new UserWeb();
			UserWeb query = userWeb.selectOne(Wrappers.<UserWeb>lambdaQuery().eq(UserWeb::getUserId, user.getId()));
			if (ObjectUtil.isNotEmpty(query)) {
				detail.set("ext", query.getUserExt());
			}
		} else if (userEnum == UserEnum.APP) {
			UserApp userApp = new UserApp();
			UserApp query = userApp.selectOne(Wrappers.<UserApp>lambdaQuery().eq(UserApp::getUserId, user.getId()));
			if (ObjectUtil.isNotEmpty(query)) {
				detail.set("ext", query.getUserExt());
			}
		} else {
			UserOther userOther = new UserOther();
			UserOther query = userOther.selectOne(Wrappers.<UserOther>lambdaQuery().eq(UserOther::getUserId, user.getId()));
			if (ObjectUtil.isNotEmpty(query)) {
				detail.set("ext", query.getUserExt());
			}
		}
		userInfo.setDetail(detail);
		return userInfo;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public UserInfo userInfo(UserOauth userOauth) {
		UserOauth uo = userOauthService.getOne(Wrappers.<UserOauth>query().lambda().eq(UserOauth::getUuid, userOauth.getUuid()).eq(UserOauth::getSource, userOauth.getSource()));
		UserInfo userInfo;
		if (Func.isNotEmpty(uo) && Func.isNotEmpty(uo.getUserId())) {
			userInfo = this.userInfo(uo.getUserId());
			userInfo.setOauthId(Func.toStr(uo.getId()));
		} else {
			userInfo = new UserInfo();
			if (Func.isEmpty(uo)) {
				userOauthService.save(userOauth);
				userInfo.setOauthId(Func.toStr(userOauth.getId()));
			} else {
				userInfo.setOauthId(Func.toStr(uo.getId()));
			}
			User user = new User();
			user.setAccount(userOauth.getUsername());
			user.setTenantId(userOauth.getTenantId());
			userInfo.setUser(user);
			userInfo.setRoles(Collections.singletonList(GUEST_NAME));
		}
		return userInfo;
	}

	@Override
	public boolean grant(String userIds, String roleIds) {
		User user = new User();
		user.setRoleId(roleIds);
		return this.update(user, Wrappers.<User>update().lambda().in(User::getId, Func.toLongList(userIds)));
	}

	@Override
	public boolean resetPassword(String userIds) {
		User user = new User();
		user.setPassword(DigestUtil.encrypt(CommonConstant.DEFAULT_PASSWORD));
		user.setUpdateTime(DateUtil.now());
		return this.update(user, Wrappers.<User>update().lambda().in(User::getId, Func.toLongList(userIds)));
	}

	@Override
	public boolean updatePassword(Long userId, String oldPassword, String newPassword, String newPassword1) {
		User user = getById(userId);
		if (!newPassword.equals(newPassword1)) {
			throw new ServiceException("请输入正确的确认密码!");
		}
		if (!user.getPassword().equals(DigestUtil.hex(oldPassword))) {
			throw new ServiceException("原密码不正确!");
		}
		return this.update(Wrappers.<User>update().lambda().set(User::getPassword, DigestUtil.hex(newPassword)).eq(User::getId, userId));
	}

	@Override
	public boolean removeUser(String userIds) {
		if (Func.contains(Func.toLongArray(userIds), AuthUtil.getUserId())) {
			throw new ServiceException("不能删除本账号!");
		}
		return deleteLogic(Func.toLongList(userIds));
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void importUser(List<UserExcel> data, Boolean isCovered) {
		data.forEach(userExcel -> {
			User user = Objects.requireNonNull(BeanUtil.copy(userExcel, User.class));
			// 设置用户平台
			user.setUserType(Func.toInt(DictCache.getKey(DictEnum.USER_TYPE, userExcel.getUserTypeName()), 1));
			// 设置部门ID
			user.setDeptId(Func.toStrWithEmpty(SysCache.getDeptIds(userExcel.getTenantId(), userExcel.getDeptName()), StringPool.EMPTY));
			// 设置岗位ID
			user.setPostId(Func.toStrWithEmpty(SysCache.getPostIds(userExcel.getTenantId(), userExcel.getPostName()), StringPool.EMPTY));
			// 设置角色ID
			user.setRoleId(Func.toStrWithEmpty(SysCache.getRoleIds(userExcel.getTenantId(), userExcel.getRoleName()), StringPool.EMPTY));
			// 设置租户ID
			if (!AuthUtil.isAdministrator() || StringUtil.isBlank(user.getTenantId())) {
				user.setTenantId(AuthUtil.getTenantId());
			}
			// 覆盖数据
			if (isCovered) {
				// 查询用户是否存在
				User oldUser = UserCache.getUser(userExcel.getTenantId(), userExcel.getAccount());
				if (oldUser != null && oldUser.getId() != null) {
					user.setId(oldUser.getId());
					this.updateUser(user);
					return;
				}
			}
			// 获取默认密码配置
			String initPassword = ParamCache.getValue(DEFAULT_PARAM_PASSWORD);
			user.setPassword(initPassword);
			this.submit(user);
		});
	}

	@Override
	public List<UserExcel> exportUser(Wrapper<User> queryWrapper) {
		List<UserExcel> userList = baseMapper.exportUser(queryWrapper);
		userList.forEach(user -> {
			user.setUserTypeName(DictCache.getValue(DictEnum.USER_TYPE, user.getUserType()));
			user.setRoleName(StringUtil.join(SysCache.getRoleNames(user.getRoleId())));
			user.setDeptName(StringUtil.join(SysCache.getDeptNames(user.getDeptId())));
			user.setPostName(StringUtil.join(SysCache.getPostNames(user.getPostId())));
		});
		return userList;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean register(String tenantId, String account, String password, String captcha, String phone, Integer sign) {
		Tenant tenant = SysCache.getTenant(tenantId);
		if (tenant == null || tenant.getId() == null) {
			throw new ServiceException("租户信息错误!");
		}
		JSONObject registerConfig = JSONObject.parseObject(ParamCache.getValue("register.config"));
		JSONObject tenantConfig = registerConfig.getJSONObject(tenantId);
		User user = baseMapper.selectOne(Wrappers.<User>query().lambda().eq(User::getTenantId, tenantId).eq(User::getAccount, account).eq(User::getIsDeleted, LykjConstant.DB_NOT_DELETED));
		if (!Func.isNull(user)) {
			throw new ServiceException("该账户已注册，请尝试登录!");
		} else {
			// 其他住户下有该账户
//			user = baseMapper.selectOne(Wrappers.<User>query().lambda().eq(User::getAccount, account).eq(User::getIsDeleted, LykjConstant.DB_NOT_DELETED));
//			if (!Func.isNull(user)) {
//				user.setId(null);
//				user.setUid(null);
//				user.setSysBalance(BigDecimal.ZERO);
//				user.setSysIntegral(BigDecimal.ZERO);
//				user.setSysContribute(BigDecimal.ZERO);
//				user.setOrdersTotal(BigDecimal.ZERO);
//				user.setBonusOrders(BigDecimal.ZERO);
//				user.setBonusTotal(BigDecimal.ZERO);
//				user.setBonusLimit(BigDecimal.ZERO);
//				user.setBonusStatus(0);
//				user.setEarningsTotal(BigDecimal.ZERO);
//				user.setExtractLimit(BigDecimal.ZERO);
//				user.setUserSign(0);
//			} else {
			user = new User();
			user.setUserType(2);
			user.setAccount(account);
			user.setPassword(DigestUtil.hex(password));
			user.setName(account);
			user.setPhone(account);
//			}
		}
//		if (sign == null && Func.isNull(user)) {
		//去第三方注册
//		JSONObject returnJson = znApiUtils.register("2", account, password, captcha);
//		if (returnJson.getInteger("status") != 200) {
//			JSONObject content = returnJson.getJSONObject("content");
//			throw new ServiceException(content.getString("msg"));
//		}
//		}
		smsService.verificationRegisterVerifyCode(account, captcha);
		Long spreadId = 0L;
		if (Func.isNotBlank(phone) && !"0".equals(phone)) {
			//获取推荐人ID
			User userSpread = baseMapper.selectOne(Wrappers.<User>query().lambda().eq(User::getTenantId, tenantId).eq(User::getAccount, phone).eq(User::getIsDeleted, LykjConstant.DB_NOT_DELETED));
			if (userSpread != null) {
				spreadId = userSpread.getUid();
			}
		}
		user.setTenantId(tenantId);
		user.setSpreadId(spreadId);
		user.setAvatar(tenantConfig.getString("avatar"));
		user.setRoleId(tenantConfig.getString("roleId"));
		user.setDeptId(tenantConfig.getString("deptId"));
		user.setPostId(tenantConfig.getString("postId"));
		return this.registerSubmit(user);
	}

	@Override
	public boolean updateDayWithdrawalLimit(String userIds, String dayWithdrawalLimit) {
		return baseMapper.updateDayWithdrawalLimit(userIds, dayWithdrawalLimit) > 0;
	}

	@Override
	public boolean updateSumWithdrawalLimit(String userIds, String sumWithdrawalLimit) {
		return baseMapper.updateSumWithdrawalLimit(userIds, sumWithdrawalLimit) > 0;
	}

	@Override
	public boolean updateBonusStatus(String userIds, String bonusStatus) {
		return baseMapper.updateBonusStatus(userIds, bonusStatus) > 0;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean registerSubmit(User user) {
		if (StringUtil.isBlank(user.getTenantId())) {
			user.setTenantId(LykjConstant.ADMIN_TENANT_ID);
		}
		String tenantId = user.getTenantId();
		Tenant tenant = SysCache.getTenant(tenantId);
		if (Func.isNotEmpty(tenant)) {
			Integer accountNumber = tenant.getAccountNumber();
			if (tenantProperties.getLicense()) {
				String licenseKey = tenant.getLicenseKey();
				String decrypt = DesUtil.decryptFormHex(licenseKey, TenantConstant.DES_KEY);
				accountNumber = JsonUtil.parse(decrypt, Tenant.class).getAccountNumber();
			}
			Long tenantCount = baseMapper.selectCount(Wrappers.<User>query().lambda().eq(User::getTenantId, tenantId));
			if (accountNumber != null && accountNumber > 0 && accountNumber <= tenantCount) {
				throw new ServiceException("当前租户已到最大账号额度!");
			}
		}
		Long userCount = baseMapper.selectCount(Wrappers.<User>query().lambda().eq(User::getTenantId, tenantId).eq(User::getAccount, user.getAccount()));
		if (userCount > 0L && Func.isEmpty(user.getId())) {
			throw new ServiceException(StringUtil.format("当前用户 [{}] 已存在!", user.getAccount()));
		}
		return save(user) && submitUserDept(user);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean activate(String tenantId, String account, String password, String captcha) {
		Tenant tenant = SysCache.getTenant(tenantId);
		if (tenant == null || tenant.getId() == null) {
			throw new ServiceException("租户信息错误!");
		}

		User user = baseMapper.selectOne(Wrappers.<User>query().lambda()
			.eq(User::getTenantId, tenantId)
			.eq(User::getAccount, account)
//			.ne(User::getZnUserId, null)
//			.ne(User::getZnUserId, "")
			.eq(User::getIsDeleted, LykjConstant.DB_NOT_DELETED));
		if (user == null) {
			throw new ServiceException("该用户不存在或者已激活，请重新尝试!");
		}
		//去第三方注册
//		JSONObject returnJson = znApiUtils.register("2", account, password, captcha);
//		if (returnJson.getInteger("status") != 200) {
//			throw new ServiceException(returnJson.getString("content"));
//		}
		smsService.verificationRegisterVerifyCode(account, captcha);

		user.setPassword(DigestUtil.hex(password));
		return this.updateById(user);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean registerGuest(User user, Long oauthId) {
		Tenant tenant = SysCache.getTenant(user.getTenantId());
		if (tenant == null || tenant.getId() == null) {
			throw new ServiceException("租户信息错误!");
		}
		UserOauth userOauth = userOauthService.getById(oauthId);
		if (userOauth == null || userOauth.getId() == null) {
			throw new ServiceException("第三方登陆信息错误!");
		}
		user.setRealName(user.getName());
		user.setAvatar(userOauth.getAvatar());
		user.setRoleId(StringPool.MINUS_ONE);
		user.setDeptId(StringPool.MINUS_ONE);
		user.setPostId(StringPool.MINUS_ONE);
		boolean userTemp = this.submit(user);
		userOauth.setUserId(user.getId());
		userOauth.setTenantId(user.getTenantId());
		boolean oauthTemp = userOauthService.updateById(userOauth);
		return (userTemp && oauthTemp);
	}

	@Override
	public boolean updatePlatform(Long userId, Integer userType, String userExt) {
		if (userType.equals(UserEnum.WEB.getCategory())) {
			UserWeb userWeb = new UserWeb();
			UserWeb query = userWeb.selectOne(Wrappers.<UserWeb>lambdaQuery().eq(UserWeb::getUserId, userId));
			if (ObjectUtil.isNotEmpty(query)) {
				userWeb.setId(query.getId());
			}
			userWeb.setUserId(userId);
			userWeb.setUserExt(userExt);
			return userWeb.insertOrUpdate();
		} else if (userType.equals(UserEnum.APP.getCategory())) {
			UserApp userApp = new UserApp();
			UserApp query = userApp.selectOne(Wrappers.<UserApp>lambdaQuery().eq(UserApp::getUserId, userId));
			if (ObjectUtil.isNotEmpty(query)) {
				userApp.setId(query.getId());
			}
			userApp.setUserId(userId);
			userApp.setUserExt(userExt);
			return userApp.insertOrUpdate();
		} else {
			UserOther userOther = new UserOther();
			UserOther query = userOther.selectOne(Wrappers.<UserOther>lambdaQuery().eq(UserOther::getUserId, userId));
			if (ObjectUtil.isNotEmpty(query)) {
				userOther.setId(query.getId());
			}
			userOther.setUserId(userId);
			userOther.setUserExt(userExt);
			return userOther.insertOrUpdate();
		}
	}

	@Override
	public UserVO platformDetail(User user) {
		User detail = baseMapper.selectOne(Condition.getQueryWrapper(user));
		UserVO userVO = UserWrapper.build().entityVO(detail);
		if (userVO.getUserType().equals(UserEnum.WEB.getCategory())) {
			UserWeb userWeb = new UserWeb();
			UserWeb query = userWeb.selectOne(Wrappers.<UserWeb>lambdaQuery().eq(UserWeb::getUserId, user.getId()));
			if (ObjectUtil.isNotEmpty(query)) {
				userVO.setUserExt(query.getUserExt());
			}
		} else if (userVO.getUserType().equals(UserEnum.APP.getCategory())) {
			UserApp userApp = new UserApp();
			UserApp query = userApp.selectOne(Wrappers.<UserApp>lambdaQuery().eq(UserApp::getUserId, user.getId()));
			if (ObjectUtil.isNotEmpty(query)) {
				userVO.setUserExt(query.getUserExt());
			}
		} else {
			UserOther userOther = new UserOther();
			UserOther query = userOther.selectOne(Wrappers.<UserOther>lambdaQuery().eq(UserOther::getUserId, user.getId()));
			if (ObjectUtil.isNotEmpty(query)) {
				userVO.setUserExt(query.getUserExt());
			}
		}
		return userVO;
	}


	@Override
	public IPage<UserVO> selectUserPage(IPage<UserVO> page, UserVO user) {
		return page.setRecords(baseMapper.selectUser(page, user));
	}

	@Override
	public List<UserVO> lazyList(String tenantId, Long parentId, Map<String, Object> param) {
		// 设置租户ID
		if (AuthUtil.isAdministrator()) {
			tenantId = StringPool.EMPTY;
		}
		String paramTenantId = Func.toStr(param.get(TENANT_ID));
		if (Func.isNotEmpty(paramTenantId) && AuthUtil.isAdministrator()) {
			tenantId = paramTenantId;
		}
		return baseMapper.lazyList(tenantId, parentId, param);
	}

	//平台余额转账
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean transferMoney(Long otherUserId, BigDecimal number) {
		// 转账
//		if (getTodaySum(AuthUtil.getUserId(),0).add(number).compareTo(BigDecimal.valueOf(20000)) > 0) {
//			throw new ServiceException("今日转账超限，请明天再转！（单日累计限额20000）");
//		}
		// TODO 转出方
		User outUser = this.getById(AuthUtil.getUserId());//BeanUtil.copy(UserCache.getUser(AuthUtil.getUserId()), LykjUser.class)
		if (number.compareTo(outUser.getSysBalance()) > 0) {
			throw new ServiceException("平台账户余额不足!");
		}
		//减少余额
		baseMapper.decBalance(number,outUser.getId());
		// 计算余额
//		BigDecimal outUserBalance = outUser.getSysBalance();
//		outUserBalance=outUserBalance.subtract(number);
		//转出记录
		userBillService.insertBill(
			outUser.getTenantId(),
			outUser.getId(),
			otherUserId,
			null,
			0,//0转出1转入
			number,
			BigDecimal.ZERO,
			"平台余额转账",
			0,//0现金1积分2贡献值
			7,//0增加1减少2奖励3兑换4充值5提现6购物7转账8红包9收益10运费
//			outUserBalance,
			"余额转账,[" + outUser.getId() + "] to [" + otherUserId + "],金额[" + number + "],手续费[" + BigDecimal.ZERO + "],实际到账[" + number + "]"//,余额[" + outUserBalance + "]
		);
//		UserBill outBill = new UserBill();
//		outBill.setTenantId(outUser.getTenantId());
//		outBill.setUserId(outUser.getId());
//		outBill.setOtherUserId(otherUserId);
//		outBill.setLinkId(null);
//		outBill.setPm(0);//0转出1转入
//		outBill.setTitle("平台余额转账");
//		outBill.setCategory(0);//0现金1积分2贡献值
//		outBill.setType(7);//0增加1减少2奖励3兑换4充值5提现6购物7转账8红包9收益
//		outBill.setNumber(number);
//		outBill.setService(BigDecimal.ZERO);
//		outBill.setActual(outBill.getNumber().subtract(outBill.getService()));
//		outBill.setBalance(outUser.getSysBalance().subtract(number));
//		outBill.setRemark("余额转账,[" + outUser.getId() + "] to [" + otherUserId + "],金额[" + outBill.getNumber() + "],手续费[" + outBill.getService() + "],实际到账[" + outBill.getActual() + "],余额[" + outBill.getBalance() + "]");
//		userBillService.save(outBill);
		//扣除余额
//		outUser.setSysBalance(outUser.getSysBalance().subtract(number));
//		this.updateById(outUser);

		// TODO 转入方
		User inUser = this.getById(otherUserId);
		//增加余额
		baseMapper.inBalance(number,inUser.getId());
		// 计算余额
//		BigDecimal inUserBalance = inUser.getSysBalance();
//		inUserBalance=inUserBalance.add(number);
		//转入记录
		userBillService.insertBill(
			inUser.getTenantId(),
			inUser.getId(),
			outUser.getId(),
			null,
			1,//0转出1转入
			number,
			BigDecimal.ZERO,
			"平台余额转账",
			0,//0现金1积分2贡献值
			7,//0增加1减少2奖励3兑换4充值5提现6购物7转账8红包9收益10运费
//			inUserBalance,
			"余额转账，[" + outUser.getId() + "] to [" + inUser.getId() + "],金额[" + number + "],手续费[" + BigDecimal.ZERO + "],实际到账[" + number + "]"//,余额[" + inUserBalance + "]
		);
//		UserBill inBill = new UserBill();
//		inBill.setTenantId(inUser.getTenantId());
//		inBill.setUserId(inUser.getId());
//		inBill.setOtherUserId(outUser.getId());
//		inBill.setLinkId(null);
//		inBill.setPm(1);//0转出1转入
//		inBill.setTitle("余额转账");
//		inBill.setCategory(0);//0现金1积分2贡献值
//		inBill.setType(7);//0增加1减少2奖励3兑换4充值5提现6购物7转账8红包9收益
//		inBill.setNumber(number);
//		inBill.setService(BigDecimal.ZERO);
//		inBill.setActual(inBill.getNumber().subtract(inBill.getService()));
//		inBill.setBalance(inUser.getSysBalance().add(inBill.getActual()));
//		inBill.setRemark("余额转账，[" + outUser.getId() + "] to [" + inUser.getId() + "],金额[" + outBill.getNumber() + "],手续费[" + inBill.getService() + "],实际到账[" + inBill.getActual() + "],余额[" + inBill.getBalance() + "]");
//		userBillService.save(inBill);
		//增加余额 扣掉手续费
//		inUser.setSysBalance(inUser.getSysBalance().add(inBill.getActual()));
//		this.updateById(inUser);
		return true;
	}

	//贡献值兑换余额
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean transferContribute(BigDecimal number) {
		JSONObject serviceCharge = JSONObject.parseObject(paramService.getValue("service.charge"));
		JSONObject contributeValue = JSONObject.parseObject(paramService.getValue("contribute.value"));
		User user = this.getById(AuthUtil.getUserId());
//		BigDecimal userBalance = user.getSysBalance();
//		BigDecimal userContribute = user.getSysContribute();
		if (number.compareTo(user.getSysContribute()) > 0) {
			throw new ServiceException("贡献值余额不足!");
		}
		// 兑换金额=贡献值*贡献值现在价值
		BigDecimal newNumber = number.multiply(contributeValue.getBigDecimal("now"));
		// 服务费=兑换金额*手续费
		BigDecimal service = newNumber.multiply(serviceCharge.getBigDecimal("withdrawal"));

		//减少贡献值，增加余额
		baseMapper.transferContribute(number,newNumber.subtract(service),user.getId());

		//贡献值
//		userContribute = userContribute.subtract(number);
		//转出记录 减少贡献值
		userBillService.insertBill(
			user.getTenantId(),
			user.getId(),
			user.getId(),
			null,
			0,//0转出1转入
			number,
			BigDecimal.ZERO,
			"贡献值兑换",
			2,//0现金1积分2贡献值
			3,//0增加1减少2奖励3兑换4充值5提现6购物7转账8红包9收益10运费
//			userContribute,
			"贡献值兑换,贡献值[" + number + "],汇率[" + contributeValue.get("now") + "],手续费[" + BigDecimal.ZERO + "],实际[" + number + "]"//,余额[" + userContribute + "]
		);
//		UserBill outBill = new UserBill();
//		outBill.setTenantId(user.getTenantId());
//		outBill.setUserId(user.getId());
//		outBill.setOtherUserId(user.getId());
//		outBill.setLinkId(null);
//		outBill.setPm(0);//0转出1转入
//		outBill.setTitle("贡献值兑换");
//		outBill.setCategory(2);//0现金1积分2贡献值
//		outBill.setType(3);//0增加1减少2奖励3兑换4充值5提现6购物7转账8红包9收益
//		outBill.setNumber(number);
//		outBill.setService(BigDecimal.ZERO);
//		outBill.setActual(outBill.getNumber().subtract(outBill.getService()));
//		outBill.setBalance(user.getSysContribute().subtract(number));
//		outBill.setRemark("贡献值兑换,贡献值[" + outBill.getNumber() + "],汇率[" + contributeValue.get("now") + "],手续费[" + outBill.getService() + "],实际到账[" + outBill.getActual() + "],余额[" + outBill.getBalance() + "]");
//		userBillService.save(outBill);

		//账户余额=余额+兑换金额-服务费
//		userBalance = userBalance.add(newNumber.subtract(service));
		//转入记录 增加余额
		userBillService.insertBill(
			user.getTenantId(),
			user.getId(),
			user.getId(),
			null,
			1,//0转出1转入
			newNumber,
			service,
			"贡献值兑换",
			0,//0现金1积分2贡献值
			3,//0增加1减少2奖励3兑换4充值5提现6购物7转账8红包9收益10运费
//			userBalance,
			"贡献值兑换,金额[" + newNumber + "],汇率[" + contributeValue.get("now") + "],手续费[" + service + "],实际到账[" + newNumber.subtract(service) + "]"//,余额[" + userBalance + "]
		);
//		UserBill inBill = new UserBill();
//		inBill.setTenantId(user.getTenantId());
//		inBill.setUserId(user.getId());
//		inBill.setOtherUserId(user.getId());
//		inBill.setLinkId(null);
//		inBill.setPm(1);//0转出1转入
//		inBill.setTitle("贡献值兑换");
//		inBill.setCategory(0);//0现金1积分2贡献值
//		inBill.setType(3);//0增加1减少2奖励3兑换4充值5提现6购物7转账8红包9收益
//		inBill.setNumber(number.multiply(contributeValue.getBigDecimal("now")));
//		inBill.setService(number.multiply(contributeValue.getBigDecimal("now")).multiply(service));
//		inBill.setActual(inBill.getNumber().subtract(inBill.getService()));
//		inBill.setBalance(user.getSysBalance().add(inBill.getActual()));
//		inBill.setRemark("贡献值兑换,金额[" + inBill.getNumber() + "],汇率[" + contributeValue.get("now") + "],手续费[" + inBill.getService() + "],实际到账[" + inBill.getActual() + "],余额[" + inBill.getBalance() + "]");
//		userBillService.save(inBill);

//		//扣除贡献值
//		user.setSysContribute(user.getSysContribute().subtract(number));
//		//增加余额
//		user.setSysBalance(user.getSysBalance().add(inBill.getActual()));
//		this.updateById(user);
		return true;
	}

	// 提现失败退款
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean refund(Long userId, BigDecimal number, Long linkId) {
		User user = this.getById(userId);//BeanUtil.copy(UserCache.getUser(AuthUtil.getUserId()), LykjUser.class)
//		BigDecimal userBalance = user.getSysBalance();
//		userBalance = userBalance.add(number);
		//增加余额
		this.inBalance(number,userId);
		//转入记录
		userBillService.insertBill(
			user.getTenantId(),
			user.getId(),
			0L,
			linkId,
			1,//0转出1转入
			number,
			BigDecimal.ZERO,
			"提现失败退款",
			0,//0现金1积分2贡献值
			5,//0增加1减少2奖励3兑换4充值5提现6购物7转账8红包9收益10运费
//			userBalance,
			"提现失败退款,金额[" + number + "],手续费[" + BigDecimal.ZERO + "],实际到账[" + number + "]"//,余额[" + userBalance + "]
		);
//		UserBill inBill = new UserBill();
//		inBill.setTenantId(outUser.getTenantId());
//		inBill.setUserId(outUser.getId());
//		inBill.setOtherUserId(0L);
//		inBill.setLinkId(linkId);
//		inBill.setPm(1);//0转出1转入
//		inBill.setTitle("提现失败退款");
//		inBill.setCategory(0);//0现金1积分2贡献值
//		inBill.setType(5);//0增加1减少2奖励3兑换4充值5提现6购物7转账8红包9收益
//		inBill.setNumber(number);
//		inBill.setService(BigDecimal.ZERO);
//		inBill.setActual(inBill.getNumber().subtract(inBill.getService()));
//		inBill.setBalance(outUser.getSysBalance().add(number));
//		inBill.setRemark("提现失败退款,金额[" + inBill.getNumber() + "],手续费[" + inBill.getService() + "],实际到账[" + inBill.getActual() + "],余额[" + inBill.getBalance() + "]");
//		userBillService.save(inBill);
		//扣除余额
//		outUser.setSysBalance(outUser.getSysBalance().add(number));
//		this.updateById(outUser);
		return true;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean recharge(Map<String, Object> params) {
		BigDecimal number = new BigDecimal(params.get("number").toString());
		StringBuffer title = new StringBuffer();
		title.append("系统");
		User user = this.getById(Long.parseLong(params.get("userId").toString()));
		Integer pm = 0;
//		BigDecimal balance = BigDecimal.ZERO;
		if ("0".equals(params.get("category").toString())) {//现金
			if (user.getSysBalance() == null) user.setSysBalance(BigDecimal.ZERO);
			title.append("余额");
			if ("0".equals(params.get("pm").toString())) {//扣除
				title.append("减少");
				user.setSysBalance(user.getSysBalance().subtract(new BigDecimal(params.get("number").toString())));
				pm = 0;
//				balance = user.getSysBalance();
			} else {//增加
				title.append("增加");
				user.setSysBalance(user.getSysBalance().add(new BigDecimal(params.get("number").toString())));
				pm = 1;
//				balance = user.getSysBalance();
			}
			if (user.getSysBalance().compareTo(BigDecimal.ZERO) < 0) {
				throw new ServiceException("平台账户余额不足!");
			}
		} else if ("1".equals(params.get("category").toString())) {//积分
			if (user.getSysIntegral() == null) user.setSysIntegral(BigDecimal.ZERO);
			title.append("积分");
			if ("0".equals(params.get("pm").toString())) {//扣除
				title.append("减少");
				user.setSysIntegral(user.getSysIntegral().subtract(new BigDecimal(params.get("number").toString())));
				pm = 0;
//				balance = user.getSysIntegral();
			} else {
				title.append("增加");
				user.setSysIntegral(user.getSysIntegral().add(new BigDecimal(params.get("number").toString())));
				pm = 1;
//				balance = user.getSysIntegral();
			}
			if (user.getSysIntegral().compareTo(BigDecimal.ZERO) < 0) {
				throw new ServiceException("平台账户积分不足!");
			}
		} else  if ("2".equals(params.get("category").toString())){
			if (user.getSysContribute() == null) user.setSysContribute(BigDecimal.ZERO);
			title.append("贡献值");
			if ("0".equals(params.get("pm").toString())) {//扣除
				title.append("减少");
				user.setSysContribute(user.getSysContribute().subtract(new BigDecimal(params.get("number").toString())));
				pm = 0;
//				balance = user.getSysContribute();
			} else {
				title.append("增加");
				user.setSysContribute(user.getSysContribute().add(new BigDecimal(params.get("number").toString())));
				pm = 1;
//				balance = user.getSysContribute();
			}
			if (user.getSysContribute().compareTo(BigDecimal.ZERO) < 0) {
				throw new ServiceException("平台账户贡献值不足!");
			}
		}else if ("3".equals(params.get("category").toString())) {//消费专享金
			if (user.getSysIntegral() == null) user.setSysIntegral(BigDecimal.ZERO);
			title.append("消费专享金");
			if ("0".equals(params.get("pm").toString())) {//扣除
				title.append("减少");
				user.setEarmarkedMoney(user.getEarmarkedMoney().subtract(new BigDecimal(params.get("number").toString())));
				pm = 0;
//				balance = user.getSysIntegral();
			} else {
				title.append("增加");
				user.setEarmarkedMoney(user.getEarmarkedMoney().add(new BigDecimal(params.get("number").toString())));
				pm = 1;
//				balance = user.getSysIntegral();
			}
			if (user.getEarmarkedMoney().compareTo(BigDecimal.ZERO) < 0) {
				throw new ServiceException("消费专享金不足!");
			}
		}
		this.updateById(user);
		//转出记录
		userBillService.insertBill(
			user.getTenantId(),
			user.getId(),
			0L,
			null,
			pm,//0转出1转入
			number,
			BigDecimal.ZERO,
			title.toString(),
			Integer.parseInt(params.get("category").toString()),//0现金1积分2贡献值
			Integer.parseInt(params.get("pm").toString()),//0增加1减少2奖励3兑换4充值5提现6购物7转账8红包9收益10运费
//			balance,
			title + "," + params.get("remark").toString() + ",金额[" + number + "],手续费[" + BigDecimal.ZERO + "],实际到账[" + number + "]"//,余额[" + balance + "]
		);
//		UserBill userBill = new UserBill();
//		userBill.setTenantId(user.getTenantId());
//		userBill.setUserId(user.getId());
//		userBill.setOtherUserId(0L);
//		userBill.setLinkId(null);
//		userBill.setPm(pm);//0转出1转入
//		userBill.setTitle(title.toString());
//		userBill.setCategory(Integer.parseInt(params.get("category").toString()));//0现金1积分2贡献值
//		userBill.setType(Integer.parseInt(params.get("pm").toString()));//0减少1增加2奖励3兑换4充值5提现6购物7转账8红包9收益
//		userBill.setNumber(new BigDecimal(params.get("number").toString()));
//		userBill.setService(BigDecimal.ZERO);
//		userBill.setActual(userBill.getNumber().subtract(userBill.getService()));
//		userBill.setBalance(balance);
//		userBill.setRemark(title + "," + params.get("remark").toString() + ",金额[" + userBill.getNumber() + "],手续费[" + userBill.getService() + "],实际到账[" + userBill.getActual() + "],余额[" + userBill.getBalance() + "]");
//		userBillService.save(userBill);
		return true;
	}
	//红包收益
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean bonus(Long bonusId) {
		UserBonus userBonus = userBonusService.getById(bonusId);
		// 防止重复领取
		if (userBonus.getStatus() == 1) {
			return true;
		}
		userBonusService.bonusStatus(userBonus.getId());

		List<UserBill> listBill = userBillService.list(Wrappers.<UserBill>lambdaQuery()
			.eq(UserBill::getUserId, userBonus.getUserId())
			.eq(UserBill::getLinkId, userBonus.getOrderId())
			.like(UserBill::getCreateTime, DateUtil.format(new Date(), DateUtil.PATTERN_DATE))
		);
		// 防止重复领取
		if (listBill != null && listBill.size() > 1) {
			userBonusService.bonusDeleted(userBonus.getId());
			return true;
		}
		User user = this.getById(userBonus.getUserId());
//		BigDecimal userBalance = user.getSysBalance();
		// 增加累计分红和余额
//		this.inBonusTotal(userBonus.getNumber(),user.getId());

		UserOrder userOrder = userOrderMapper.selectById(userBonus.getOrderId());
		//判断是2022-07-15之前的红包是否已经领取过，如果领取过，则不再领取
		if (userOrder.getUpdateTime().before(DateUtil.parse("2022-07-15", DateUtil.PATTERN_DATE))) {
			// 15号前 分红
			this.inBalance(userBonus.getNumber(),user.getId());
		}else{
			//15号后 放到专项金里
			baseMapper.inEarmarkedMoney(userBonus.getNumber(),user.getId());
		}

		// 计算余额
//		userBalance = userBalance.add(userBonus.getNumber());
		//转入记录
		userBillService.insertBill(
			user.getTenantId(),
			user.getId(),
			user.getId(),
			userBonus.getOrderId(),
			1,//0转出1转入
			userBonus.getNumber(),
			BigDecimal.ZERO,
			"红包收益",
			0,//0现金1积分2贡献值
			8,//0增加1减少2奖励3兑换4充值5提现6购物7转账8红包9收益10运费
//			userBalance,
			"红包收益,金额[" + userBonus.getNumber() + "],手续费[" + BigDecimal.ZERO + "],实际到账[" + userBonus.getNumber() + "]"//,余额[" + userBalance + "]
		);
		return true;
	}

	//转户提现申请
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean withdrawal(String accountName, String accountNumber, BigDecimal amount) {
		User user = this.getById(AuthUtil.getUserId());
		if (user.getOpenWithdrawal()!=0) {
			throw new ServiceException("暂未开通提现功能");
		}
		String withdrawalStatus = paramService.getValue("withdrawal.status");
		if (!"true".equals(withdrawalStatus)) {
			String withdrawalMsg = paramService.getValue("withdrawal.msg");
			throw new ServiceException(withdrawalMsg);
		}
		BigDecimal sumUserAmount = userExtractService.sumUserAmount(user.getId());
		// 提现 每天限制提现一次和单次金额不能超过1000
		if (amount.compareTo(user.getDayWithdrawalLimit()) > 0 || getTodaySum(AuthUtil.getUserId(), 1).compareTo(BigDecimal.ZERO) > 0) {
			throw new ServiceException("今日超限（每日限提1次，每次限提"+user.getDayWithdrawalLimit()+"）！");
		}
		if (sumUserAmount.compareTo(user.getSumWithdrawalLimit())>0){
			throw new ServiceException("总提现超限（限提"+user.getSumWithdrawalLimit()+"）！");
		}
		// 协议商品（提现） {"commodityId":"G00005","commodityPrice":0.5,"commodityQuantity":100000,"feeRate":0}
		JSONObject protocolCommodity = JSONObject.parseObject(ParamCache.getValue("protocol.commodity"));
		// 手续费
		BigDecimal feeRate = BigDecimal.ZERO;//protocolCommodity.getBigDecimal("feeRate");
		// 求数量
		BigDecimal count = amount.divide(protocolCommodity.getBigDecimal("commodityPrice"));
		if (new BigDecimal(count.intValue()).compareTo(count) != 0) {
			throw new ServiceException("提现金额请输入" + protocolCommodity.get("commodityPrice") + "的倍数");
		}
		// 提现手续费 {"withdrawal":0.2}
		JSONObject serviceCharge = JSONObject.parseObject(ParamCache.getValue("service.charge"));
		//手续费
		BigDecimal withdrawal = serviceCharge.getBigDecimal("withdrawal");

//		BigDecimal userBalance = user.getSysBalance();
		// 总手续费 提现金额*平台手续费+数量*协议商品手续费
		BigDecimal service = amount.multiply(withdrawal).add(count.multiply(feeRate));
		//最终金额=提现金额+总手续费
		BigDecimal number = amount.add(service);
		// 判断余额>（提现金额+提现金额*手续费+数量*协议商品手续费）
		if (user.getSysBalance().compareTo(number) < 0) {
			throw new ServiceException("平台账户余额不足!余额[" + user.getSysBalance() + "],提现金额[" + amount + "]+手续费[" + service + "]");
		}
//		userBalance = userBalance.subtract(number);//user.setSysBalance(user.getSysBalance().subtract(number));//余额-（提现金额+提现金额*平台手续费+数量*协议商品手续费）
		// 扣除余额
		this.decBalance(number, user.getId());
		//转出记录
		userBillService.insertBill(
			user.getTenantId(),
			user.getId(),
			0L,
			null,
			0,//0转出1转入
			amount,
			service,
			"平台余额提现",
			0,//0现金1积分2贡献值
			5,//0增加1减少2奖励3兑换4充值5提现6购物7转账8红包9收益10运费
//			userBalance,
			"平台余额提现,金额[" + amount + "],手续费[" + service + "],实际金额[" + number + "]"//,余额[" + userBalance + "]
		);
		//生产提现申请记录
		UserExtract userExtract = new UserExtract();
		userExtract.setUserId(user.getId());
		userExtract.setZnUserId(user.getZnUserId());
		userExtract.setZnCommodityId(protocolCommodity.getString("commodityId"));
		userExtract.setZnCommodityPrice(protocolCommodity.getBigDecimal("commodityPrice"));
		userExtract.setQuantity(count.intValue());
		userExtract.setAccountName(accountName);
		userExtract.setAccountNumber(accountNumber);
		userExtract.setAmount(amount);
		userExtract.setService(service);
		userExtract.setArrivalAmount(number);
		userExtract.setRemark("申请提现");
		userExtract.setStatus(0);
		userExtractService.save(userExtract);
		return true;
	}

	/**
	 * 计算每天转出金额
	 *
	 * @param userId
	 * @param type   类型0转账1提现
	 * @return
	 */
	public BigDecimal getTodaySum(Long userId, int type) {
		BigDecimal todaySum = BigDecimal.ZERO;
//		List<UserBill> listBill = userBillService.list(Wrappers.<UserBill>lambdaQuery()
//			.eq(UserBill::getUserId, userId)
//			.eq(UserBill::getType, 7)
//			.eq(UserBill::getPm,0)
//			.like(UserBill::getCreateTime, DateUtil.format(new Date(), DateUtil.PATTERN_DATE)));
//		if (listBill != null && listBill.size() > 0) {
//			for (UserBill ub : listBill) {
//				todaySum = todaySum.add(ub.getNumber());
//			}
//		}
		List<UserExtract> listExtract = userExtractService.list(Wrappers.<UserExtract>lambdaQuery()
			.eq(UserExtract::getUserId, AuthUtil.getUserId())
			.like(UserExtract::getCreateTime, DateUtil.format(new Date(), DateUtil.PATTERN_DATE))
		);
		if (listExtract != null && listExtract.size() > 0) {
			for (UserExtract ue : listExtract) {
				todaySum = todaySum.add(ue.getAmount());
			}
		}
		return todaySum;
	}


	/**
	 * 增加余额
	 *
	 * @param number
	 * @param id
	 */
	@Override
//	@Transactional(rollbackFor = Exception.class)
	public void inBalance(BigDecimal number, Long id) {
		baseMapper.inBalance(number, id);
	}

	/**
	 * 扣除余额
	 *
	 * @param number
	 * @param id
	 */
	@Override
//	@Transactional(rollbackFor = Exception.class)
	public void decBalance(BigDecimal number, Long id) {
		baseMapper.decBalance(number, id);
	}

	@Override
	public void decEarmarkedMoney(BigDecimal number, Long id) {
		baseMapper.decEarmarkedMoney(number, id);
	}

	/**
	 * 增加积分
	 *
	 * @param number
	 * @param id
	 */
	@Override
//	@Transactional(rollbackFor = Exception.class)
	public void inIntegral(BigDecimal number, Long id) {
		baseMapper.inIntegral(number, id);
	}

	/**
	 * 扣除积分
	 *
	 * @param number
	 * @param id
	 */
	@Override
//	@Transactional(rollbackFor = Exception.class)
	public void decIntegral(BigDecimal number, Long id) {
		baseMapper.decIntegral(number, id);
	}

	/**
	 * 增加贡献值
	 *
	 * @param number
	 * @param id
	 */
	@Override
//	@Transactional(rollbackFor = Exception.class)
	public void inContribute(BigDecimal number, Long id) {
		baseMapper.inContribute(number, id);
	}

	/**
	 * 扣除贡献值
	 *
	 * @param number
	 * @param id
	 */
	@Override
//	@Transactional(rollbackFor = Exception.class)
	public void decContribute(BigDecimal number, Long id) {
		baseMapper.decContribute(number, id);
	}

	/**
	 * 累计订单总额
	 *
	 * @param number
	 * @param id
	 */
	@Override
//	@Transactional(rollbackFor = Exception.class)
	public void inOrdersTotal(BigDecimal number, Long id) {
//		baseMapper.inOrdersTotal(number, id);
	}

	/**
	 * 累计分红订单总额
	 *
	 * @param number
	 * @param id
	 */
	@Override
//	@Transactional(rollbackFor = Exception.class)
	public void inBonusOrders(BigDecimal number, Long id) {
//		baseMapper.inBonusOrders(number, id);
	}

	/**
	 * 累计领取分红
	 *
	 * @param number
	 * @param id
	 */
	@Override
//	@Transactional(rollbackFor = Exception.class)
	public void inBonusTotal(BigDecimal number, Long id) {
//		baseMapper.inBonusTotal(number, id);
	}

	/**
	 * 累计收益
	 *
	 * @param number
	 * @param id
	 */
	@Override
//	@Transactional(rollbackFor = Exception.class)
	public void inEarningsTotal(BigDecimal number, Long id) {
		baseMapper.inEarningsTotal(number, id);
	}

	/**
	 * 分配分红资格
	 * @param status
	 * @param id
	 */
	@Override
//	@Transactional(rollbackFor = Exception.class)
	public void bonusStatus(Integer status, Long id){
		baseMapper.bonusStatus(status,id);
	}

	@Override
	public void bonusStatus(Integer status) {
		baseMapper.allBonusStatus(status);
	}

	/**
	 * 会有升级
	 * @param id
	 */
	@Override
//	@Transactional(rollbackFor = Exception.class)
	public void upgrade(Long id){
		baseMapper.upgrade(id);
	}

	@Override
	public List<com.lykj.modules.shop.excel.UserExcel> export(User user){
		return baseMapper.export(user);
	}
}
